package net.wicp.tams.component.tools;

import java.util.Collections;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.dom.Element;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.json.JSONArray;
import org.apache.tapestry5.json.JSONObject;

import net.wicp.tams.commons.apiext.StringUtil;

public abstract class ComponentsAssist {

	/***
	 * Render按钮信息
	 * 
	 * @param writer
	 * @param buts
	 * @param messages
	 * @param resources
	 */
	public static void renderButs(MarkupWriter writer, JSONArray buts, Messages messages,
			ComponentResources resources) {
		if (buts == null || buts.length() == 0) {
			return;
		}
		List<JSONObject> rendList = TapestryAssist.getJSONObjectList(buts);
		Collections.sort(rendList, new CompartorJson());

		if (CollectionUtils.isNotEmpty(rendList)) {
			for (JSONObject jsonObj : rendList) {
				Element element = writer.element("a", "id", jsonObj.getString("id"), "href", "javascript:void(0)",
						"class", "easyui-linkbutton");//
				if (jsonObj.has("style")) {
					element.attribute("style", jsonObj.getString("style"));
					jsonObj.remove("style");
				}
				if (!jsonObj.has("plain")) {// 把默认改为true
					jsonObj.put("plain", true);
				}

				String textKey = jsonObj.getString("text");
				String text = null;
				if (messages != null && messages.contains(textKey)) {
					text = messages.get(textKey);
				}
				if (StringUtil.isNull(text)
						&& resources.getPage().getComponentResources().getMessages().contains(textKey)) {
					text = resources.getPage().getComponentResources().getMessages().get(textKey);// 得到页面的国际化信息
				} else {
					text = textKey;
				}
				element.text(text);
				jsonObj.remove("text");
				jsonObj.remove("index");
				element.attribute("data-options", jsonObj.toString());
				writer.end();
			}
		}
	}

}
